<?php
/** .-------------------------------------------------------------------
 * | Author: OkCoder <1046512080@qq.com>
 * | Git: https://www.gitee.com/okcoder
 * | Copyright (c) 2012-2019, www.i5920.com. All Rights Reserved.
 * '-------------------------------------------------------------------*/

namespace OkCoder\PHPAes;

//php aes加密类
class Main
{
    public $iv = null;
    public $key = null;
    public $bit = 128;
    private $cipher;

    public function __construct($key = 'abcdef1234567890', $iv = '0987654321fedcba', $bit = 128, $mode = 'cbc')
    {
        if (empty($bit) || empty($key) || empty($iv) || empty($mode))
            return NULL;
        $this->bit = $bit;
        $this->key = substr(md5($key), 0, 16);
        $this->iv = substr(md5($iv), 0, 16);
        $this->mode = $mode;
        switch ($this->bit) {
            case 192:
                $this->cipher = MCRYPT_RIJNDAEL_192;
                break;
            case 256:
                $this->cipher = MCRYPT_RIJNDAEL_256;
                break;
            default:
                $this->cipher = MCRYPT_RIJNDAEL_128;
        }
        switch ($this->mode) {
            case 'ecb':
                $this->mode = MCRYPT_MODE_ECB;
                break;
            case 'cfb':
                $this->mode = MCRYPT_MODE_CFB;
                break;
            case 'ofb':
                $this->mode = MCRYPT_MODE_OFB;
                break;
            case 'nofb':
                $this->mode = MCRYPT_MODE_NOFB;
                break;
            default:
                $this->mode = MCRYPT_MODE_CBC;
        }
    }

    /**
     * 加密
     * @param string $data　明文
     * @return string　返回密文(已base64加密的密文)
     */
    public function encrypt($data)
    {
        if (version_compare(PHP_VERSION, '7.1.0', '<')) {
            $data = mcrypt_encrypt($this->cipher, $this->key, $data, $this->mode, $this->iv);
        } else {
            $data = openssl_encrypt($data, "AES-128-CBC", $this->key, OPENSSL_RAW_DATA, $this->iv);
        }
        $data = base64_encode($data);
        return $data;
    }

    /**
     * 解密
     * @param string $data 密文(已base64加密的密文)
     * @return string　明文
     */
    public function decrypt($data)
    {
        if (version_compare(PHP_VERSION, '7.1.0', '<')) {
            $data = mcrypt_decrypt($this->cipher, $this->key, base64_decode($data), $this->mode, $this->iv);
            $data = rtrim($data, "\O");
        } else {
            $data = openssl_decrypt(base64_decode($data), "AES-128-CBC", $this->key, OPENSSL_RAW_DATA, $this->iv);
        }
        return $data;
    }
}
